from django.core.files.storage import Storage
from fdfs_client.client import Fdfs_client

from dailyfresh import settings


class FDFSStorage(Storage):
    """ fast dfs 文件存储类"""

    def __init__(self, client_conf=None, base_url=None):
        """初始化"""
        if client_conf is None:
            client_conf = settings.FDFS_CLIENT_CONF
        self.client_conf = client_conf
        if base_url is None:
            base_url = settings.FDFS_URL
        self.base_url = base_url

    def open(self, name, mode='rb'):
        """打开文件是使用"""
        pass

    def _save(self, name, content):
        """
        保存文件是使用
        :param name:  选择的上次文件的名字
        :param content: 包含你上传文件内容的File对象
        :return:
        """
        # 创建一个fdfs_client对象
        client = Fdfs_client(self.client_conf)

        # 上次文件到fast dfs
        res = client.upload_by_buffer(content.read())

        # return dict
        # {
        #     'Group name': group_name,
        #     'Remote file_id': remote_file_id,
        #     'Status': 'Upload successed.',
        #     'Local file name': '',
        #     'Uploaded size': upload_size,
        #     'Storage IP': storage_ip
        # }
        if res.get('Status') != 'Upload successed.':
            # 上次失败
            raise Exception('上传文件到fast dfs 失败')
        # 获取到返回的文件ID
        filename = res.get('Remote file_id')
        return filename

    def exists(self, name):
        """文件名是否存在"""
        return False

    def url(self, name):
        """返回访问文件的url路径"""
        print(self.base_url + name)
        return self.base_url + name
